use super::bpb::BIOSParameterBlock;
use super::fat::Fat;
use super::inode::{Fat32INode, NodeType};
use crate::drivers::block::block_device_test;
use crate::fs::block::{BlockManager, BLOCK_SIZE};
use alloc::string::ToString;
use alloc::{string::String, sync::Arc, vec, vec::Vec};
use spin::Mutex;
pub struct Fat32FS {
    //block_manager: Arc<BlockManager>,
    //bpb: BIOSParameterBlock,
    //fat: Fat,
    root_node: Fat32INode,
}

impl Fat32FS {
    pub fn new(block_manager: Arc<BlockManager>) -> Self {
        // 读取第一个扇区，并构造必要的数据
        let mut buf: [u8; BLOCK_SIZE] = [0; BLOCK_SIZE];
        block_manager.read_block(0, &mut buf);
        //println!("{:?}", buf);
        //let bm_ref = Arc::new(block_manager);
        let bpb = BIOSParameterBlock::build(&buf);
        assert!(bpb.is_valid(), "invalid bpb");
        let fat = Fat {
            start_block_id: bpb.reserved_sector_num as usize * bpb.blocks_per_sector,
            ids_per_block: BLOCK_SIZE / 4,
            max_cluster_id: (bpb.sector_per_fat as usize * bpb.bytes_per_sector as usize) / 4 - 1,
            block_manager: block_manager.clone(),
            blocks_per_cluster: bpb.blocks_per_cluster,
            blocks_offset_to_data: bpb.blocks_offset_to_data,
        };
        Fat32FS {
            root_node: Fat32INode {
                node_type: NodeType::Dir,
                name: "/".to_string(),
                size: 0,
                start_cluster_id: bpb.root_cluster_idx as usize,
                fat: Arc::new(fat),
                block_manager: block_manager.clone(),
            },
        }
    }
    pub fn ls(&self, path: &str) -> Vec<Fat32INode> {
        // 读取根节点
        // 从根节点开始索引到当前path
        // 读取path下的所有
        // 先简单地只读取根节点下面的节点
        //vec![]
        self.root_node.ls()
    }
}
